package chaos.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


public class ZIPResourceManager implements ResourceManager {
	File file;
	ZipFile zip;
	Vector<InputStream> streams;
	boolean autoFixPath = true;
	
	public ZIPResourceManager(String file) throws IOException {
		this.file = new File(file);
		zip = new ZipFile(this.file);
	}
	
	public ZIPResourceManager(File file) throws IOException {
		this.file = file;
		zip = new ZipFile(this.file);
	}
	
	public String[] getMDXList() {
		Enumeration enu = zip.entries();
		Vector<String> vec = new Vector();
		while(enu.hasMoreElements()) {
			ZipEntry ent = (ZipEntry)enu.nextElement();
			if(!ent.getName().toLowerCase().endsWith(".mdx")) continue;
			vec.add(ent.getName());
		}
		if(vec.size() <= 0) return null;
		String list[] = new String[vec.size()];
		vec.toArray(list);
		return list;
	}

	public void init() throws Exception {
		zip = new ZipFile(file);
		streams = new Vector<InputStream>();
	}

	public void close() {
		Enumeration enu = streams.elements();
		while(enu.hasMoreElements()) {
			InputStream stream = (InputStream)enu.nextElement();
			try {
				stream.close();
			} catch (Exception e) {
			}
		}
		try {
			zip.close();
		} catch (Exception e) {
		}
	}
	
	protected String toCompataiblePath(String path) {
		String cpath = path.replace('\\', '/').toLowerCase();
		Enumeration enu = zip.entries();
		while(enu.hasMoreElements()) {
			ZipEntry entry = (ZipEntry)enu.nextElement();
			if(cpath.equals( entry.getName().toLowerCase() )) {
				return entry.getName();
			}
		}
		return path;
	}

	public InputStream getInputStream(String path) {
		try {
			String cPath = toCompataiblePath(path);
			ZipEntry entry = zip.getEntry(cPath);
			System.out.println("RPATH : "+path +", CPATH : "+cPath);
			if(entry == null) return null;
			InputStream stream = zip.getInputStream(entry);
			streams.add(stream);
			return stream;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}